<template>
	<view class="container">
		<!-- 话题标题 -->
		<view class="title-wrap">
			<view class="title-label">话题标题</view>
			<wd-input v-model="formData.title" :maxlength="30" show-word-limit />
		</view>

		<!-- 话题内容 -->
		<textarea class="textarea" v-model="formData.content" placeholder="分享你的经历，或提个问题..." />

		<!-- 图片上传 -->
		<view style="margin: 20rpx 0">
			<wd-upload ref="uploader" v-model:file-list="imageList" :before-upload="beforeUpload" :auto-upload="false"
				multiple :limit="9"></wd-upload>
		</view>

		<!-- 发布按钮 -->
		<wd-button block @click="onPublish">发布话题</wd-button>
	</view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app';
import { ref, reactive } from 'vue';
import { uploadImage } from '@/utils/upload.js';
import { baseAPI } from '@/api/index.js';

//页面公共变量
const imageList = ref([]);
const uploader = ref();

const formData = reactive({
	title: '',
	content: '',
	media: []
});

// 页面生命周期
onLoad(() => { });
onShow(() => { });

// 页面函数
function beforeUpload({ files, fileList, resolve }) {
	imageList.value = fileList;
	resolve(true);
}

async function onPublish() {
	if (!formData.title.trim()) {
		uni.showToast({
			title: '请输入话题标题',
			icon: 'none'
		});
		return;
	}

	if (!formData.content.trim()) {
		uni.showToast({
			title: '请输入话题内容',
			icon: 'none'
		});
		return;
	}

	uni.showLoading({
		title: '发布中'
	});

	// 上传图片
	formData.media = [];
	for (let file of imageList.value) {
		const imgUrl = await uploadImage(file);
		formData.media.push(imgUrl);
	}

	baseAPI.post('discuss/publish', formData).then((res) => {
		if (res.code === 200) {
			uni.showToast({
				title: '发布成功',
				icon: 'success'
			});

			setTimeout(() => {
				uni.switchTab({
					url: '/pages/discuss/index'
				});
			}, 1500);
		}

		uni.hideLoading();
	});
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
}

.title-wrap {
	margin-bottom: 30rpx;

	.title-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}

	.title-input {
		width: 100%;
		padding: 20rpx;
		background-color: #f7f8fa;
		border-radius: 12rpx;
		font-size: 30rpx;
		border: none;
	}
}

.textarea {
	width: 100%;
	min-height: 300rpx;
	padding: 20rpx;
	background-color: #f7f8fa;
	border-radius: 12rpx;
	font-size: 28rpx;
	border: none;
	margin-bottom: 30rpx;
}
</style>
